import {Component} from 'vue';
import {ComponentRegister} from './types';

/**
 * 组件管理器
 * 用于注册和获取组件
 */
class ComponentManager {

  // 组件映射
  private static readonly componentMap: Map<string, ComponentRegister> = new Map();

  /**
   * 注册组件
   * @param type 组件类型
   * @param component 组件
   * @param defaultProps 组件默认属性
   */
  public static register<T extends Record<string, any> = Record<string, any>>(type: string, component: Component, defaultProps?: T): void {
    this.componentMap.set(type, {
      type,
      component,
      defaultProps
    });
  }

  /**
   * 批量注册组件
   * @param components 组件列表
   */
  public static registerComponents(components: ComponentRegister[]): void {
    components.forEach(item => {
      this.componentMap.set(item.type, item);
    });
  }

  /**
   * 获取组件
   * @param type 组件类型
   */
  public static getComponent<T extends Record<string, any>>(type: string): ComponentRegister<T> | undefined {
    const component = this.componentMap.get(type);
    if (!component) return undefined;
    return component as ComponentRegister<T>;
  }

  /**
   * 获取所有组件
   */
  public static getAllComponents(): ComponentRegister[] {
    return Array.from(this.componentMap.values());
  }

  /**
   * 检查组件是否存在
   * @param type 组件类型
   */
  public static has(type: string): boolean {
    return this.componentMap.has(type);
  }

  /**
   * 移除组件
   * @param type 组件类型
   */
  public static remove(type: string): boolean {
    return this.componentMap.delete(type);
  }

  /**
   * 清空所有组件
   */
  public static clear(): void {
    this.componentMap.clear();
  }
}

export default ComponentManager;
